package com.jackstraw.jack_base.remote_command.pool;

import com.jackstraw.jack_base.remote_command.pool.entity.SessiontConnectionConfig;
import com.jcraft.jsch.Session;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.pool2.impl.GenericObjectPool;

@Data
@Slf4j
public class SessionConnectionPool {

    public final static String SESSIONCONNECTIONPOOL_BEANNAME = "SessionConnectionPool";
    public final static String SESSIONCONNECTIONPOOL_ROOT_BEANNAME = "RootSessionConnectionPool";
    public final static String ROOT = "Root";

    private String connName;
    private SessionConnectionFactory sessionConnectionFactory;
    private SessiontConnectionConfig sessiontConnectionConfig;
    private GenericObjectPool<Session> sessionGenericObjectPool;

    public SessionConnectionPool(SessionConnectionFactory sessionConnectionFactory) {
        this.sessionConnectionFactory = sessionConnectionFactory;
        this.sessiontConnectionConfig = this.sessionConnectionFactory.getSessiontConnectionConfig();
        sessionGenericObjectPool = new GenericObjectPool<>(this.sessionConnectionFactory, this.sessiontConnectionConfig);
        this.connName = this.sessiontConnectionConfig.getConnectName();
    }

    /**
     * 借 获取一个连接对象
     *
     * @return
     * @throws Exception
     */
    public Session borrowObject() throws Exception {
        return this.borrowObject(sessionGenericObjectPool.getMaxWaitMillis());
    }

    /**
     * 借 获取一个连接对象
     *
     * @param borrowMaxWaitMillis
     * @return
     * @throws Exception
     */
    public Session borrowObject(long borrowMaxWaitMillis) throws Exception {
        Session session = sessionGenericObjectPool.borrowObject(borrowMaxWaitMillis);
        if (ObjectUtils.isEmpty(session)) {
            log.error("获取到的session为null");
        }
        if (!session.isConnected()) {
            //说明拿到的session对象非空没有启用
            //移除改对象
            sessionGenericObjectPool.invalidateObject(session);
            session = sessionConnectionFactory.create();
            sessionGenericObjectPool.addObject();
        }
        return session;
    }

    /**
     * 还 归还一个连接对象
     *
     * @param obj
     */
    public void returnObject(Session obj) {
        if (ObjectUtils.isNotEmpty(obj)) {
            sessionGenericObjectPool.returnObject(obj);
        }
    }

}
